<template>
  <view class="pre-project-detail">
    <view class="project-content">
      <view class="section-title"><view class="title">基本信息</view></view>
      <view class="form-box">
        <view class="form-item">
          <view class="item-name">项目名称</view>
          <view class="item-content">
            <input placeholder="请输入项目名称" :disabled="!isEdit" v-model="name" maxlength="100" />
          </view>
        </view>
        <view class="form-item">
          <view class="item-name">项目地址</view>
          <view class="item-content">
            <input placeholder="请输入项目地址" :disabled="!isEdit" v-model="address" maxlength="500" />
            <i v-if="isEdit" class="suffix-icon location iconfont icon-location" @click="chooseProjectAddr()" />
          </view>
        </view>
        <view class="form-item">
          <view class="item-name">现有灯型</view>
          <view class="item-content">
            <input placeholder="请输入现有灯型" :disabled="!isEdit" v-model="lampDesc" maxlength="50" />
          </view>
        </view>
        <view class="form-item">
          <view class="item-name">预估数量</view>
          <view class="item-content">
            <input type="number" placeholder="请输入灯具数量" :disabled="!isEdit" v-model="lampCount" maxlength="10" />
            <view class="suffix-unit">盏</view>
          </view>
        </view>
        <view class="form-item">
          <view class="item-name">联系人</view>
          <view class="item-content">
            <input placeholder="请输入联系人" :disabled="!isEdit" v-model="contact" maxlength="50" />
          </view>
        </view>
        <view v-if="createTime" class="form-item">
          <view class="item-name">创建时间</view>
          <view class="item-content">
            {{createTime}}
          </view>
        </view>
        <view v-if="modifyTime" class="form-item">
          <view class="item-name">更新时间</view>
          <view class="item-content">
            {{modifyTime}}
          </view>
        </view>
      </view>

      <view class="section-title"><view class="title">备注说明/拜访记录</view></view>
      <view class="form-box">
        <view class="form-item memo-content"><textarea class="memo" :disabled="!isEdit" placeholder="请输入内容" maxlength="5000" auto-height v-model="memo" @change="updateMemo"></textarea>
        </view>
      </view>

      <view class="section-title"><view class="title">项目照片</view></view>
      <view class="form-box">
        <view v-for="(item, index) in pictures" :key="item.key" class="picture-item">
          <view class="file-box">
            <view v-if="isEdit && !item.src" class="add-file" @click="chooseFile(item)"><view class="iconfont icon-add"></view></view>
            <view v-else class="file-preview-box">
              <view class="file-index">{{ index + 1 }}</view>
              <view v-if="isEdit" class="delete-file" @click="clearFile(item)"><view class="iconfont icon-close"></view></view>
              <image class="file-preview" :src="item.src" mode="aspectFill" @click="previewImg(item)"></image>
            </view>
          </view>
          <view class="file-info">
            <uni-easyinput class="picture-desc" :disabled="!isEdit" maxlength="100" v-model="item.desc" placeholder="请输入照片描述"></uni-easyinput>
            <view v-if="isEdit" class="delete-pic" @click="deletePicture(item)">删除</view>
          </view>
        </view>
        <view v-if="isEdit" class="add-picture" @click="addPicture()">
          <text class="iconfont icon-add"></text> 添加照片
        </view>
      </view>

      <view class="btn-box">
        <view v-if="!isEdit" class="btn-item success" @click="toEdit()">修改</view>
        <view v-if="isEdit" class="btn-item primary" @click="save()">确定</view>
        <view v-if="isEdit && projectId" class="btn-item danger" @click="deleteProject()">删除</view>
      </view>
    </view>
    <uni-popup ref="deleteProjectDialog" type="dialog">
      <uni-popup-dialog type="error" cancelText="否" confirmText="是" content="确定要删除项目？" @confirm="doDelete()"></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import mixin from '@/mixins/index.js'
import { CONFIG } from '@/envs/_/config'
import { formatDate, getImagePath, getGUID } from '@/utils/index.js'
const chooseLocation = requirePlugin('chooseLocation')
export default {
  mixins: [mixin],
  data() {
    return {
      isEdit: true,
      projectId: '',
      name: '',
      projectType: '',
      address: '',
      lampDesc: '',
      lampType: '',
      lampCount: '',
      contact: '',
      createTime: '',
      modifyTime: '',
      memo: '',
      pictures: []
    }
  },
  onShow() {
    const self = this
    const location = chooseLocation.getLocation()
    if (location) {
      console.log(location)
      self.address = location.address
    }
  },
  mounted() {
    const self = this
    if (self.params.id) {
      self.projectId = self.params.id
      self.getProjectInfo()
    }
  },
  methods: {
    getProjectInfo() {
      const self = this
      uni.request({
        url: '/pre_project/get',
        data: {
          id: self.projectId
        },
        success(result) {
          if (result.data.success && result.data.data) {
            self.isEdit = false
            const projectInfo = result.data.data
            self.name = projectInfo.name || ''
            self.address = projectInfo.address || ''
            self.lampDesc = projectInfo.description || ''
            self.lampCount = Math.floor(projectInfo.qty) || ''
            self.contact = projectInfo.contact || ''
            self.createTime = formatDate(projectInfo.create_time, 'yyyy-MM-dd hh:mm:ss')
            self.modifyTime = formatDate(projectInfo.modify_time, 'yyyy-MM-dd hh:mm:ss')
            self.memo = projectInfo.remark || ''
            if (projectInfo.imgs) {
              try {
                const pictures = JSON.parse(projectInfo.imgs)
                pictures.forEach((item) => {
                  item.src = getImagePath(item.path)
                })
                self.pictures = pictures
              } catch (e) {
                console.error(e)
              }
            }
          }
        }
      })
    },
    chooseProjectAddr() {
      const self = this
      const key = CONFIG.MAP_KEY
      const referer = CONFIG.PROJECT_NAME
      wx.navigateTo({
        url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer
      })
    },
    updateMemo(e) {
      this.memo = e.detail.value
    },
    chooseFile(target) {
      const self = this
      uni.chooseImage({
        count: 1,
        success(result) {
          console.log('choose file', result)
          const tempPath = result.tempFilePaths[0] || ''
          self.uploadFile(tempPath, path => {
            target.path = path
            target.src = getImagePath(path)
          })
        }
      })
    },
    clearFile(target) {
      const self = this
      target.path = ''
      target.src = ''
    },
    uploadFile(filePath, callback) {
      const self = this
      uni.uploadFile({
        url: '/sys/upload',
        filePath,
        name: 'file',
        success(result) {
          if (result.data.url) {
            if (callback instanceof Function) {
              callback(result.data.url)
            }
          }
        }
      })
    },
    previewImg(target) {
      const self = this
      uni.previewImage({
        urls: [target.src]
      })
    },
    deletePicture(target) {
      const self = this
      self.pictures = self.pictures.filter((item) => item.key !== target.key)
    },
    addPicture() {
      const self = this
      if (self.pictures.length >= 9) {
        uni.showToast({
          icon: 'none',
          title: '最多添加9张照片'
        })
        return
      }
      self.pictures.push({
        key: getGUID(),
        path: '',
        desc: '',
        src: ''
      })
    },
    toEdit() {
      this.isEdit = true
    },
    save() {
      const self = this
      self.name = self.name.trim()
      self.address = self.address.trim()
      self.lampDesc = self.lampDesc.trim()
      self.contact = self.contact.trim()
      self.memo = self.memo.trim()
      if (!self.name) {
        uni.showToast({
          icon: 'none',
          title: '请输入项目名称'
        })
        return
      }
      let url = '/pre_project/add'
      const imgs = Array.from(self.pictures, (item) => {
        return {
          key: item.key,
          path: item.path,
          desc: item.desc.trim()
        }
      })
      const data = {
        name: self.name,
        address: self.address,
        description: self.lampDesc,
        qty: Math.floor(self.lampCount) || 0,
        contact: self.contact,
        remark: self.memo,
        imgs: JSON.stringify(imgs)
      }
      if (self.projectId) {
        url = '/pre_project/modify'
        data.id = self.projectId
      }
      uni.request({
        url,
        method: 'POST',
        data,
        success(result) {
          if (result.data.success) {
            uni.showToast({
              icon: 'none',
              title: '保存成功'
            })
            self.isEdit = false
          }
        }
      })
    },
    deleteProject() {
      this.$refs.deleteProjectDialog.open()
    },
    doDelete() {
      const self = this
      if (!self.projectId) {
        return
      }
      uni.request({
        url: '/pre_project/del',
        method: 'POST',
        data: {
          id: self.projectId
        },
        success(result) {
          self.goBack()
        }
      })
    },
    goBack() {
      uni.navigateBack();
    }
  }
}
</script>

<style lang="scss" scoped>
.pre-project-detail {
  padding: 30rpx 30rpx 70rpx;
  min-height: 100vh;
  background-color: $primary;
}
.section-title {
  @include section-title;
  .title {
    color: $primary;
  }
}
.form-box {
  + .section-title {
    margin-top: 50rpx;
  }
}
.picture-item {
  margin-top: 20rpx;
  .file-box {
    .add-file {
      width: 100%;
      height: 360rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 10rpx;
      border: 2rpx dashed $border-base;
      font-size: 72rpx;
      color: $text-base;
    }
    .file-preview-box {
      position: relative;
      .file-index {
        position: absolute;
        width: 30rpx;
        height: 30rpx;
        line-height: 30rpx;
        text-align: center;
        top: 0;
        left: 0;
        color: $white;
        background-color: $primary;
        font-size: $font-size-0;
      }
      .delete-file {
        position: absolute;
        width: 50rpx;
        height: 50rpx;
        line-height: 50rpx;
        text-align: center;
        top: 0;
        right: 0;
        color: $white;
        background-color: $danger;
        font-size: $font-size-5;
        &:after {
          content: '';
          display: block;
          position: absolute;
          left: -10rpx;
          right: -10rpx;
          top: -10rpx;
          bottom: -10rpx;
        }
      }
      .file-preview {
        width: 100%;
        height: 360rpx;
        display: block;
      }
    }
  }
  .file-info {
    margin-top: 20rpx;
    display: flex;
    .picture-desc {
      flex: 1;
    }
    .delete-pic {
      margin-left: 20rpx;
      flex: none;
      display: flex;
      align-items: center;
      border-radius: 10rpx;
      border: 2rpx solid $danger;
      color: $danger;
      font-size: $font-size-1;
      padding: 10rpx 30rpx;
    }
  }
}
.add-picture {
  margin-top: 30rpx ;
  border: 2rpx dashed $primary;
  border-radius: 10rpx;
  padding: 15rpx;
  font-size: $font-size-3;
  text-align: center;
  .iconfont {
    margin-right: 10rpx;
  }
}

.project-content {
  position: relative;
  z-index: 2;
  background-color: $white;
  border-radius: 10rpx;
  padding: 30rpx;
  .btn-box {
    justify-content: center;
  }
}
.item-name {
  font-size: $font-size-3;
  font-weight: bold;
}
.item-content {
  font-size: $font-size-2;
  display: flex;
  align-items: center;
  text-align: right;
  justify-content: flex-end;
  width: 360rpx;
  input,
  .input {
    flex: 1;
    text-align: right;
  }
  /deep/ {
    .uni-date-x,
    .uni-select__input-placeholder {
      font-size: $font-size-2;
    }
  }
  .suffix-icon {
    flex: none;
    width: 44rpx;
    &.location {
      color: $success;
    }
  }
  .suffix-unit {
    flex: none;
    width: 44rpx;
    &.large {
      width: 72rpx;
    }
  }
}
.form-item {
  padding: 32rpx 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 2rpx solid $border-base;
}
.memo-content {
  margin-top: 20rpx;
  border-radius: 10rpx;
  background-color: $background-base;
  border: 2rpx solid $border-light;
  padding: 12rpx 20rpx;
  textarea {
    min-height: 200rpx;
    font-size: $font-size-2;
  }
}
.btn-box {
  margin-top: 50rpx;
  .btn-item {
    border-radius: 10rpx;
    width: 100%;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: $font-size-3;
    color: $white;
    font-weight: bold;
    + .btn-item {
      margin-top: 20rpx;
    }
    &.primary {
      background-color: $primary;
    }
    &.success {
      background-color: $success;
    }
    &.danger {
      background-color: $danger;
    }
  }
}
</style>
